package com.jointem.yddc.utils

import android.graphics.*
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import java.security.MessageDigest

/**
 * 圆形图片
 * Created by Kevin.Lee on 2018/6/27.
 */
open class GlideCircleTransform : BitmapTransformation() {
    override fun updateDiskCacheKey(messageDigest: MessageDigest) {
    }

    override fun transform(pool: BitmapPool, toTransform: Bitmap, outWidth: Int, outHeight: Int): Bitmap? {
        return circleCrop(pool, toTransform)
    }

    private fun circleCrop(pool: BitmapPool, toTransform: Bitmap): Bitmap? {
        val size = Math.min(toTransform.width, toTransform.height)
        val x = (toTransform.width - size) / 2
        val y = (toTransform.height - size) / 2

        // TODO this could be acquired from the pool too
        val squared = Bitmap.createBitmap(toTransform, x, y, size, size)

        var result: Bitmap?
        result = pool.get(size, size, Bitmap.Config.ARGB_8888)
//        result ?: let {
//            result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
//        }

        val canvas = Canvas(result)
        val paint = Paint()
        paint.shader = BitmapShader(squared, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
        paint.isAntiAlias = true
        val r = size / 2f
        canvas.drawCircle(r, r, r, paint)
        return result
    }
}